package com.zhouxiaoge.springbatch_if_else;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

/**
 * @author gqzmy
 */
@EnableBatchProcessing
@SpringBootApplication
public class SpringBatchIfElseApplication {

    public SpringBatchIfElseApplication(JobBuilderFactory jobBuilderFactory, StepBuilderFactory stepBuilderFactory) {
        this.jobBuilderFactory = jobBuilderFactory;
        this.stepBuilderFactory = stepBuilderFactory;
    }

    private final JobBuilderFactory jobBuilderFactory;

    private final StepBuilderFactory stepBuilderFactory;

    @Bean
    public Tasklet passTasklet() {

        return (contribution, chunkContext) -> {
            System.out.println("Pass!!!");
            return RepeatStatus.FINISHED;
            // throw new RuntimeException("passTasklet异常！！！");
        };
    }

    @Bean
    public Tasklet successTasklet() {
        return (contribution, chunkContext) -> {
            System.out.println("Success!!!");
            return RepeatStatus.FINISHED;
        };
    }

    @Bean
    public Tasklet failTasklet() {
        return (contribution, chunkContext) -> {
            System.out.println("Failure!!!");
            return RepeatStatus.FINISHED;
        };
    }

    @Bean
    public Job conditionJob() {
        return jobBuilderFactory.get("conditionJob")
                .start(firstStep())
                .on("FAILED").to(failureStep())
                .from(firstStep()).on("*").to(successStep())
                .end()
                .build();
    }

    @Bean
    public Step firstStep() {
        return stepBuilderFactory.get("firstStep").tasklet(passTasklet()).build();
    }

    @Bean
    public Step successStep() {
        return stepBuilderFactory.get("successStep").tasklet(successTasklet()).build();
    }

    @Bean
    public Step failureStep() {
        return stepBuilderFactory.get("failureStep").tasklet(failTasklet()).build();
    }

    public static void main(String[] args) {
        SpringApplication.run(SpringBatchIfElseApplication.class, args);
    }
}

